# User authentication related functions
from app.utils.database import get_db_cursor, execute_query, log_database_operation
from app.utils.logging_config import app_logger

def check_password(password, stored_password):
    """Verify password (plain text comparison)"""
    return password == stored_password

@log_database_operation("get_user_by_username")
def get_user_by_username(username):
    """Get user by username"""
    result = execute_query(
        "SELECT * FROM users WHERE username = %s", 
        (username,), 
        fetch=True
    )
    return dict(result[0]) if result else None

def get_user_by_id(user_id):
    """Get user by ID"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("SELECT * FROM users WHERE user_id = %s", (user_id,))
        user = cursor.fetchone()
        return dict(user) if user else None
    finally:
        cursor.close()
        conn.close()

@log_database_operation("create_user")
def create_user(username, email, age, gender, balance, password):
    """Create user"""
    try:
        result = execute_query("""
            INSERT INTO users (username, email, age, gender, balance, password_hash)
            VALUES (%s, %s, %s, %s, %s, %s)
            RETURNING user_id
        """, (username, email, age, gender, balance, password), fetch=True, commit=True)
        
        user_id = result[0]['user_id']
        
        # Log user registration action
        app_logger.log_user_action(
            action="user_registration",
            user_id=user_id,
            details={"username": username, "email": email}
        )
        
        return user_id
    except Exception as e:
        # Log registration failure
        app_logger.log_error(
            error_type="user_registration_failed",
            error_message=str(e),
            details={"username": username, "email": email}
        )
        raise e

def update_user_balance(user_id, amount):
    """Update user balance"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("""
            UPDATE users SET balance = balance + %s WHERE user_id = %s
            RETURNING balance
        """, (amount, user_id))
        result = cursor.fetchone()
        conn.commit()
        return float(result['balance']) if result else None
    except Exception as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()

def check_user_balance(user_id, amount):
    """Check if user balance is sufficient"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("SELECT balance FROM users WHERE user_id = %s", (user_id,))
        user = cursor.fetchone()
        if not user:
            return False, "User does not exist"
        if float(user['balance']) < amount:
            return False, f"Insufficient balance, current balance: {user['balance']}, required: {amount}"
        return True, "Sufficient balance"
    finally:
        cursor.close()
        conn.close()

def deduct_user_balance(user_id, amount):
    """Deduct user balance"""
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("""
            UPDATE users SET balance = balance - %s 
            WHERE user_id = %s AND balance >= %s
            RETURNING balance
        """, (amount, user_id, amount))
        result = cursor.fetchone()
        if not result:
            raise Exception("Insufficient balance, deduction failed")
        conn.commit()
        return float(result['balance'])
    except Exception as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()
